package com.bosssoft.hr.train.jsp.example.controller;

import com.bosssoft.hr.train.jsp.example.exception.BusinessException;
import com.bosssoft.hr.train.jsp.example.pojo.User;
import com.bosssoft.hr.train.jsp.example.service.impl.UserServiceImpl;
import com.bosssoft.hr.train.jsp.example.service.UserService;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @description: 用户登录Controller获取前端表单参数，实例化为User实例通过与数据库真实的额用户信息对比 完成后进行页面跳转
 * @author: Administrator
 * @create: 2020-05-30 10:11
 * @since
 **/

@Slf4j
public class LoginController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doPost(req,resp);
        }catch (ServletException | IOException e){
            log.error(e.getMessage());
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //获取前端表单参数
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            log.info(username+password);
            //存放到类对象中
            User user = new User();
            user.setName(username);
            user.setPassword(password);
            //将用户信息保存在session
            HttpSession session = req.getSession();
            //判断登录
            boolean isAuthorized = this.authentication(user);

            if (isAuthorized){
                session.setAttribute("name",username);
                req.getRequestDispatcher("useradmin.jsp").forward(req,resp);
            }else {
                resp.sendRedirect("login.jsp");
            }
        }catch (ServletException | IOException e){
            log.error(e.getMessage(),e);
        }

    }

    /**
     *
     * @param user
     * @return
     */
    private boolean authentication(User user){
        UserService userService = new UserServiceImpl();
        try {
            return userService.authentication(user);
        }catch (BusinessException e){
            log.error(e.getLocalizedMessage());
        }

        return false;
    }
}
